package cn.edu.hzvtc.controller;

import cn.edu.hzvtc.pojo.ReturnMsg;
import cn.edu.hzvtc.pojo.User;
import cn.edu.hzvtc.service.userService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.*;

@Controller
@RequestMapping(value = "/user")
public class UserController {
    @Autowired
    private userService userService;

    //    @RequestMapping(value = "/area/areaIndex")
//    public String areaIndex(){
//        return "area/areaIndex";
//    }
    //登录验证
    @RequestMapping(value = "/login")
    @ResponseBody
    public ReturnMsg login(@RequestParam(value = "userName", required = true) String userName,
                           @RequestParam(value = "userPassword", required = true) String userPassword,
                           HttpSession session) {

        System.out.println(userName + "   " + userPassword);
        if (userName == null || userPassword == null) {
            return ReturnMsg.fail();
        }
        //此处横版从数据库中获取对用户名和密码后进行判断
        User loginUser = userService.login(userName, userPassword);
        //登录成功
        if (loginUser != null) {
            //讲用户对象添加到Session中
            session.setAttribute("loginUser", loginUser);
            System.out.println(session.getId());

            ReturnMsg returnMsg = ReturnMsg.success();
            if (loginUser.getUserType() == 1) {
                returnMsg.setTarget("area/areaIndex");
            } else if (loginUser.getUserType() == 2) {
                returnMsg.setTarget("unit/unitIndex");
            } else if (loginUser.getUserType() == 3) {
                returnMsg.setTarget("msg/msgIndex");
            } else {
                returnMsg.setTarget("");
            }
            System.out.println(returnMsg.getTarget());
            return returnMsg;

        } else {
            return ReturnMsg.fail();
        }
    }

    //获取用户登录信息
    @RequestMapping("/loginUser")
    @ResponseBody
    public ReturnMsg loginUser(HttpSession session) {
        User loginUser = (User) session.getAttribute("loginUser");

        System.out.println("loginUser=" + loginUser);

        return ReturnMsg.success().add("loginUser", loginUser);
    }


    //注销用户
    @RequestMapping("/logout")
    @ResponseBody
    public ReturnMsg logout(HttpSession session) {
        //清除session
        session.invalidate();
        //重定向到登录页面的跳转方法
        ReturnMsg returnMsg = ReturnMsg.success();
        returnMsg.setTarget("../");
        return returnMsg;
    }


    //获取所有院校管理员信息
    @RequestMapping("/areaAdmins")
    @ResponseBody
    public ReturnMsg getAreaAdmins(@RequestParam(value = "provinceId", defaultValue = "0") Integer provinceId,
                                   @RequestParam(value = "cityId", defaultValue = "0") Integer cityId,
                                   @RequestParam(value = "schoolId", defaultValue = "0") Integer schoolId,
                                   @RequestParam(value = "userName", defaultValue = "") String userName,
                                   @RequestParam(value = "pn", defaultValue = "1") Integer pn) {
        //引入PageHelper分页插件
        //在查询之前只需要传入页码以及每页的大小
        PageHelper.startPage(pn, 5);

        //startPage方法紧跟第一个select查询就是一个分页查询
        List<User> areaAdmins = userService.getAreaAdmins(provinceId, cityId, schoolId, userName);
        //使用PageInfo包装查询结果，封装了分页信息和查询出的数据，只需将pageInfo交给页面即可
        PageInfo pageInfo = new PageInfo(areaAdmins, 5);

        return ReturnMsg.success().add("pageInfo", pageInfo);
    }


    //删除院校管理员信息
    @RequestMapping(value = "/areaAdmin/{ids}", method = RequestMethod.DELETE)
    @ResponseBody
    public ReturnMsg deleteAreaAdmin(@PathVariable("ids") String ids) {

        if (userService.deleteAreaAdmin(ids)) {
            return ReturnMsg.success();
        }
        return ReturnMsg.fail();
    }


    //添加院校管理员信息
    @RequestMapping(value = "/areaAdmin", method = RequestMethod.POST)
    @ResponseBody
    public ReturnMsg saveAreaAdmin(@Valid User user, BindingResult result, HttpSession session) {
        User loginUser = (User) session.getAttribute("loginUser");
        user.setUserOperatorId(loginUser.getId());
        user.setUserOperatorTime(new Date());
        user.setUserType(2);
        user.setUserDelState(0);

        if (userService.addAreaAdmin(user) != 0) {
            return ReturnMsg.success();
        }
        return ReturnMsg.fail();
    }


    //修改弹出模态框加载院校管理员
    @RequestMapping(value = "/areaAdmin", method = RequestMethod.GET)
    @ResponseBody
    public ReturnMsg getAreaAdmin(@RequestParam(value = "id") Integer id) {
        User areaAdmin = userService.getAreaAdmin(id);
        return ReturnMsg.success().add("areaAdmin", areaAdmin);
    }


    // 修改院校管理员信息
    @RequestMapping(value = "/areaAdmin/{areaAdminId}", method = RequestMethod.PUT)
    @ResponseBody
    public ReturnMsg updateAreaAdmin(@PathVariable("areaAdminId") Integer areaAdminId, @Valid User user) {
        //修改操作
        user.setId(areaAdminId);
        userService.updateAreaAdmin(user);
        return ReturnMsg.success();
    }


    //重置密码
    @RequestMapping("/passwordReset")
    @ResponseBody
    public ReturnMsg resetPassword(@RequestParam(value = "id") Integer id) {
        userService.resetPassword(id);
        return ReturnMsg.success();
    }

    //获取所有院校管理员信息
    @RequestMapping("/users")
    @ResponseBody
    public ReturnMsg getUsers(@RequestParam(value = "unitTypeId", defaultValue = "0") Integer unitTypeId,
                                       @RequestParam(value = "unitId", defaultValue = "0") Integer unitId,
                                   @RequestParam(value = "userName", defaultValue = "") String userName,
                                   @RequestParam(value = "pn", defaultValue = "1") Integer pn ,HttpSession session) {
        //引入PageHelper分页插件
        //在查询之前只需要传入页码以及每页的大小
        PageHelper.startPage(pn, 5);
        User loginUser = (User) session.getAttribute("loginUser");
        //startPage方法紧跟第一个select查询就是一个分页查询
        List<User> Users = userService.getUsers(unitTypeId,unitId,userName,loginUser.getUserAreaId());
        //使用PageInfo包装查询结果，封装了分页信息和查询出的数据，只需将pageInfo交给页面即可
        PageInfo pageInfo = new PageInfo(Users, 5);

        return ReturnMsg.success().add("pageInfo", pageInfo);
    }

    @RequestMapping(value = "/user/{ids}",method = RequestMethod.DELETE)
    @ResponseBody
    public ReturnMsg deleteUser(@PathVariable("ids") String ids){
        if (userService.deleteUser(ids)){
            return ReturnMsg.success();
        }
        return ReturnMsg.fail();
    }


    //添加用户信息
    @RequestMapping(value = "/user", method = RequestMethod.POST)
    @ResponseBody
    public ReturnMsg saveUser(@Valid User user, BindingResult result, HttpSession session) {
        User loginUser = (User) session.getAttribute("loginUser");
        user.setUserOperatorId(loginUser.getId());
        user.setUserOperatorTime(new Date());
        user.setUserType(3);
        user.setUserAreaId(loginUser.getUserAreaId());
        user.setUserDelState(0);

        if (userService.addUser(user) != 0) {
            return ReturnMsg.success();
        }
        return ReturnMsg.fail();
    }

    //修改单位模态框保存
    @RequestMapping(value = "/user", method = RequestMethod.GET)
    @ResponseBody
    public ReturnMsg getUser(@RequestParam(value = "id") Integer id) {

        User user = userService.getUser(id);

        return ReturnMsg.success().add("user", user);
    }

    // 修改用户保存
    @RequestMapping(value = "/user/{userId}", method = RequestMethod.PUT)
    @ResponseBody
    public ReturnMsg updateUser(@PathVariable("userId") Integer userId, @Valid User user) {
        user.setId(userId);
        userService.updateUser(user);
        return ReturnMsg.success();
    }


    @RequestMapping(value = "/userUnit/{userId}", method = RequestMethod.PUT)
    @ResponseBody
    public ReturnMsg updateUserUnit(@PathVariable("userId") Integer userId, Integer[] unitIds) {
        List<Integer> unitIdList = Arrays.asList(unitIds);
        userService.updateUserUnit(userId, unitIdList);
        return ReturnMsg.success();
    }


}
